package com.saodisheng.realm;

import com.saodisheng.model.User;
import com.saodisheng.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * description:
 * 自定义realm类，用来编写一些查询方法，或者认证授权逻辑
 *
 * @author 扫地生_saodisheng
 * @date 2021/12/30
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    /**
     * 执行认证逻辑
     * @author saodisheng_liuxingwu
     * @modifyDate 2021/12/30
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取前端传递的用户名，即账号
        String userName = authenticationToken.getPrincipal().toString();
        // 从数据库中查询是否存在对应用户
//        User user = userService.getByName(userName);
        User user = null;
        if (user == null) {
            // 用户不存在直接返回null，则shiro底层就会抛出UnknownException
            return null;
        }
        // 获取数据库中的用户密码
        String passwordInDB = user.getPassword();
        // 获取保存的用户密码盐
        String salt = user.getSalt();

        // 注意第一个参数就是我们授权逻辑的主题，要一一对应
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, passwordInDB, ByteSource.Util.bytes(salt), getName());

        return authenticationInfo;
    }

    /**
     * 执行授权逻辑
     * @author saodisheng_liuxingwu
     * @modifyDate 2021/12/30
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 添加资源的授权字符串
        // 拿到shiro的基本对象
        Subject subject = SecurityUtils.getSubject();
        // 拿到对应的用户对象
        User currentUser = (User) subject.getPrincipal();
        // 给当前对象设置权限
        info.addStringPermission("currentUser.getPerms()");

        // 返回授权后的逻辑单元
        return info;
    }
}
